package utils

import (
	"azfirewall-gateway/models"
	"encoding/json"
	uuid2 "github.com/satori/go.uuid"
	"github.com/sirupsen/logrus"
	"github.com/thinkeridea/go-extend/exnet"
	"net/http"
	"strings"
)

var MainLog = logrus.New()

func CheckError(msg string, err error) {
	if err != nil {
		MainLog.Panic(msg, err)
	}
}

func GetDirAll(path string) string {
	i := strings.LastIndex(path, "/")
	dirAll := path[:i]
	return dirAll
}

func GenUUID() string {
	return uuid2.NewV4().String()
}

func ProcessResponse(rw http.ResponseWriter, ret models.ErrorCodes, msg string, dataObj interface{}) {
	responseContent := new(models.APIResponseInfo)
	responseContent.Ret = ret
	responseContent.Msg = msg
	if dataObj != nil {
		responseContent.Data = dataObj
	}
	rw.Header().Set("Content-Type", "application/json;charset=utf-8")
	rw.Header().Set("Server", "AZ-FirewallGatewayServer/1.0")
	rw.Header().Set("X-Powered-By", "CdnPlus")
	json.NewEncoder(rw).Encode(responseContent)
}

func GetRealClientIP(r *http.Request) string {
	userRealIP := exnet.ClientPublicIP(r)
	if userRealIP == "" {
		userRealIP = exnet.ClientIP(r)
	}
	return userRealIP
}
